package com.guanlin.notification.protect;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;

import com.guanlin.notification.Constants;
import com.guanlin.notification.MainActivity;
import com.guanlin.notification.R;
import com.guanlin.notification.notification.NotificationApiCompat;
import com.guanlin.notification.notification.NotificationConstants;

/**
 * 自启动：可以监听到开关机并拉起应用进程 或者 其他应用可以拉起
 * <p>
 * 白名单：加了白名单，休眠状态下不会被杀死，但是因为各大厂商对系统的修改，需要做针对性的处理
 * ，不然在有的机型上还是会被杀掉
 * https://mp.weixin.qq.com/s/Eh-OOqZ_WuKj4fmB_czS_w自启动：可以监听到开关机并拉起应用进程
 *
 *
 * 1.配置文件注册
 * 2.前台服务权限
 */
public class ProtectService extends Service {

    public static final String TAG = ProtectService.class.getSimpleName();

    public static final int PLAY_NOTIFY_ID = 0x1213;

    /**
     * 息屏 亮屏广播接受者
     */
    ScreenLockBroadcaseReceiver mScreenLockReceiver;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ====================service");
        init();
        //注册屏幕点亮 关闭广播接收者
        registerScreenLockBroadcastRecerver();
    }

    /**
     * 注册屏幕 打开 和 关闭的广播接收者
     */
    private void registerScreenLockBroadcastRecerver() {
        mScreenLockReceiver = new ScreenLockBroadcaseReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mScreenLockReceiver, intentFilter);
    }

    private void init() {
        //初始化播放器
        initMusicPlay();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: =================================service");
        //通知栏展示
        showNotifycation();
        return START_NOT_STICKY;
    }

    private void showNotifycation() {
        Log.i(TAG, "showNotifycation:============ 展示通知栏");
        NotificationApiCompat notificationApiCompat =
                new NotificationApiCompat.Builder(this
                        , NotificationConstants.NOTIFICATION_CHANNEL_ID_PROTECT
                        , NotificationConstants.NOTIFICATION_CHANNEL_NAME_PROTECT
                        , R.mipmap.ic_launcher)
                        .setBigContentView(getBigRemoteViews())
                        .setContentView(getRemoteViews())
                        .setOngoing(true)
                        .setOnlyAlertOnce(true)
                        .build();
        notificationApiCompat.notify(PLAY_NOTIFY_ID);
        //绑定通知栏
        notificationApiCompat.startForeground(this, PLAY_NOTIFY_ID);
    }

    private RemoteViews getRemoteViews() {
        final RemoteViews view = new RemoteViews(getApplication().getPackageName()
                , R.layout.protect_notify_view);
        return view;
    }

    private RemoteViews getBigRemoteViews() {
        final RemoteViews view = new RemoteViews(getApplication().getPackageName()
                , R.layout.protect_notify_big_view);
        setCommonClickPending(view);
        return view;
    }

    /**
     * @param view v
     */
    private void setCommonClickPending(RemoteViews view) {
        // cancel 取消设防
        Intent mainIntent = new Intent();
        mainIntent.setClass(getApplication(), MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        PendingIntent cancelPedingUnlock = PendingIntent.getActivity(this, 0
                , mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        view.setOnClickPendingIntent(R.id.tvUnLock, cancelPedingUnlock);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //停止音乐
        stopMusic();
        //移除屏幕 打开  关闭 广播接收者
        if (mScreenLockReceiver != null) {
            unregisterReceiver(mScreenLockReceiver);
        }
    }

    /**
     * 开启服务
     *
     * @param context
     */
    public static final void startSelf(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(context, ProtectService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    /**
     * 开启服务
     *
     * @param context
     */
    public static final void stopSelf(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(context, ProtectService.class);
        context.stopService(intent);
    }

    // <editor-fold defaultstate="collapsed" desc="播放一段音乐达到应用不容易被杀死 和 通知栏置顶的效果">
    MediaPlayer mediaPlayer;

    private void initMusicPlay() {
        mediaPlayer = MediaPlayer.create(this, R.raw.music);
        //设置声音为静音
        mediaPlayer.setVolume(0, 0);
        //设置循环播放
        mediaPlayer.setLooping(true);
        mediaPlayer.setOnPreparedListener(new MusicListenr());
        startMusic();
    }

    /**
     * 开始音乐
     */
    private void startMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
        }
    }

    /**
     * 停止音乐
     */
    private void stopMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    /**
     * 音乐播放监听
     */
    class MusicListenr implements MediaPlayer.OnPreparedListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            initSession();
        }

        /**
         * 注意这里有关 通知栏是否能置顶的问题
         */
        private void initSession() {
            try {
                MediaSessionCompat mediaSessionCompat = new MediaSessionCompat(ProtectService.this, TAG);
                mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                        | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
                PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                        .setActions(PlaybackStateCompat.ACTION_PLAY
                                | PlaybackStateCompat.ACTION_PLAY_PAUSE
                                | PlaybackStateCompat.ACTION_PREPARE
                                | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                                | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
                stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f);
                mediaSessionCompat.setPlaybackState(stateBuilder.build());
                mediaSessionCompat.setActive(true);
            } catch (Exception e) {
            }
        }
    }
    // </editor-fold>
}
